package com.book.bookprojectapplication.login.activity;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Calendar;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.hardware.Camera;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.MediaStore.Images;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import com.book.bookprojectapplication.R;
import com.tistory.whdghks913.croutonhelper.CroutonHelper;

import de.keyboardsurfer.android.widget.crouton.Style;

public class RegisterThirdActivity extends Activity {

	CroutonHelper mHelper;
	Button backregistersecondBtn, nextBtn;
	EditText registernameText, registernickText, dateedittext;
	RadioButton girlradioBtn, manradioBtn;
	RadioGroup radioGroup;
	ImageView profile1;
	private int myear, mmonth, mday;

	static int REQUEST_PICTURE = 1;
	static int REQUEST_PHOTO_ALBUM = 2;
	static String SAMPLEIMG = "photo.png";

	Bitmap bitmap;
	Context mContext = this;
	String memail, memail2, mpassword;
	String date, inputData;
	HttpResponse response;

	String inputDate, inputImg;
	Intent i;
	String url = "http://192.168.123.182:8090/test/csjinsert.do";

	// SurfaceView를 컨트롤할 SurfaceHolder 객체 선언
	private SurfaceHolder mHolder;

	// 미리보기를 위한 카메라 객체 선언
	private Camera camera = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		mHelper = new CroutonHelper(this);
		mHelper.setDuration(1000);

		setContentView(R.layout.registerthird);

		registernameText = (EditText) findViewById(R.id.registernameText);
		registernickText = (EditText) findViewById(R.id.registernickText);

		backregistersecondBtn = (Button) findViewById(R.id.backregistersecondBtn);

		i = getIntent();

		memail = i.getExtras().getString("memail1");
		memail2 = i.getExtras().getString("memail2");
		mpassword = i.getExtras().getString("mpassword");

		backregistersecondBtn.setOnClickListener(new Button.OnClickListener() {

			public void onClick(View v) {

				Intent myIntent = new Intent(getApplicationContext(),
						RegisterSecondActivity.class);

				startActivity(myIntent);

			}

		});

		girlradioBtn = (RadioButton) findViewById(R.id.girlradioBtn);
		manradioBtn = (RadioButton) findViewById(R.id.manradioBtn);
		radioGroup = (RadioGroup) findViewById(R.id.radioGroup);
		nextBtn = (Button) findViewById(R.id.nextBtn);
		nextBtn.setOnClickListener(new Button.OnClickListener() {
			@Override
			public void onClick(View v) {
				final String name = registernameText.getText().toString();
				
				final String nickname = registernickText.getText().toString();
				String radioresult = "";

				if (registernameText.getText().toString().equals("")) {
					mHelper.setStyle(Style.ALERT);
					mHelper.setText("이름을 입력해주세요");
					mHelper.show();
				} else if (!isValidName(name)) {
					mHelper.setStyle(Style.ALERT);
					mHelper.setText("한글만 입력이 가능합니다.");
					mHelper.show();

				} else if (registernickText.getText().toString().equals("")) {
					mHelper.setStyle(Style.ALERT);
					mHelper.setText("닉네임을 입력해주세요");
					mHelper.show();
				} else if (!isValidNickname(nickname)) {
					mHelper.setStyle(Style.ALERT);
					mHelper.setText("닉네임은 영문,숫자 2~6자리입력");
					mHelper.show();

				}

				if (girlradioBtn.isChecked()) {
					radioresult = "G";
					mHelper.setStyle(Style.ALERT);
					mHelper.setText("G");
					mHelper.show();

				} else if (manradioBtn.isChecked()) {
					radioresult = "B";
					mHelper.setStyle(Style.ALERT);
					mHelper.setText("B");
					mHelper.show();
				}

				mHelper.setStyle(Style.ALERT);
				mHelper.setText("nest");
				mHelper.show();

				Intent myIntent = new Intent(getApplicationContext(),

				WritingList.class);
				startActivity(myIntent);

				inputData = "?memail=" + memail + "&memail2=" + memail2
						+ "&mpassword=" + mpassword + "&mname=" + name
						+ "&mnickname=" + nickname + "&msex=" + radioresult
						+ "&mbirth=" + date;

				System.out.println(name);
				System.out.println(nickname);
				System.out.println(radioresult);
				System.out.println(date);
				System.out.println(inputDate);
				System.out.println(profile1);
				System.out.println(memail);
				System.out.println(memail2);
				System.out.println(mpassword);

				new InsertJSON().execute(url);

			}

			// validating name
			private boolean isValidName(String name) {
				String NAME_PATTERN = "^[가-힣]{2,4}$";

				Pattern pattern = Pattern.compile(NAME_PATTERN);
				Matcher matcher = pattern.matcher(name);
				return matcher.matches();
			}

			// validating nickname
			private boolean isValidNickname(String nickname) {
				String NICKNAME_PATTERN = "^(?=.*[a-zA-Z])(?=.*[!@#$%^*+=-]|.*[0-9]).{2,6}$";

				Pattern pattern = Pattern.compile(NICKNAME_PATTERN);
				Matcher matcher = pattern.matcher(nickname);
				return matcher.matches();
			}

		});

		dateedittext = (EditText) findViewById(R.id.dateedittext);
		dateedittext.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				Dialog datepicker = new DatePickerDialog(
						RegisterThirdActivity.this, dateSetListener, myear,
						mmonth, mday);

				inputDate = "?mdate=" + dateedittext.getText().toString();
				date = String.valueOf(myear) + String.valueOf(mmonth + 1)
						+ String.valueOf(mday);

				System.out.println(inputDate);
				datepicker.show();

			}
		});

		final Calendar c = Calendar.getInstance();
		myear = c.get(Calendar.YEAR);
		mmonth = c.get(Calendar.MONTH);
		mday = c.get(Calendar.DAY_OF_MONTH);
		updateDisplay();
	}

	private void updateDisplay() {

		dateedittext.setText(new StringBuilder().append(myear).append("년")
				.append(mmonth + 1).append("월").append(mday).append("일"));
	}

	DatePickerDialog.OnDateSetListener dateSetListener = new DatePickerDialog.OnDateSetListener() {

		@Override
		public void onDateSet(DatePicker view, int year, int monthOfYear,
				int dayOfMonth) {
			myear = year;
			mmonth = monthOfYear;
			mday = dayOfMonth;
			updateDisplay();

		}
	};

	// button 클릭
	Dialog dialog;

	public void onClickImg(View v) {
		profile1 = (ImageView) findViewById(R.id.profile1);

		switch (v.getId()) {
		case R.id.profile1:
			AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
			View customLayout = View.inflate(mContext, R.layout.custom_button,
					null);
			builder.setView(customLayout);
			dialog = builder.create();
			dialog.show();
			break;
		case R.id.camera:
			dialog.dismiss();
			takePicture();
			break;
		case R.id.photoAlbum:
			dialog.dismiss();
			photoAlbum();
			break;
		}
	}

	// 사진 촬영
	void takePicture() {
		// 카메라 호출 intent 생성
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		File file = new File(Environment.getExternalStorageDirectory(),
				SAMPLEIMG);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
		startActivityForResult(intent, REQUEST_PICTURE);

	}

	// 사진 불러오기
	void photoAlbum() {
		// photo Album 호출 intent 생성
		Intent intent = new Intent(Intent.ACTION_PICK);
		intent.setType(Images.Media.CONTENT_TYPE);
		intent.setData(Images.Media.EXTERNAL_CONTENT_URI);
		startActivityForResult(intent, REQUEST_PHOTO_ALBUM);
	}

	// 촬영한 사진을 수정하기 위해서
	Bitmap loadPicture() {
		File file = new File(Environment.getExternalStorageDirectory(),
				SAMPLEIMG);
		BitmapFactory.Options option = new BitmapFactory.Options();
		option.inSampleSize = 10;
		return BitmapFactory.decodeFile(file.getAbsolutePath(), option);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);

		if (resultCode != RESULT_OK)
			return;

		if (requestCode == REQUEST_PICTURE) {

			profile1.setImageBitmap(loadPicture());
		}

		if (requestCode == REQUEST_PHOTO_ALBUM) {
			profile1.setImageURI(data.getData());
		}
	}

	private class InsertJSON extends AsyncTask<String, Void, Void> {

		@Override
		protected Void doInBackground(String... urls) {

			System.out.println("doInBackground ()");
			InputStream is = null;
			String data = inputData;

			// Download JSON data from URL
			try {
				HttpClient httpclient = new DefaultHttpClient();
				HttpPost httppost = new HttpPost(urls[0] + data);
				response = httpclient.execute(httppost);
				HttpEntity entity = response.getEntity();
				is = entity.getContent();

				// Convert response to string

				BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8);
				StringBuilder sb = new StringBuilder();
				String line = null;

			} catch (Exception e) {
				Log.e("log_tag", "Error converting result " + e.toString());
			}

			return null;

		}

		@Override
		protected void onPostExecute(Void args) {

			System.out.println("!!!!!!!!!!!!!!!!!!!!!!!!!!!");
		}

	}

}
